package com.leo.javase.thread.itcast;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 子线程循环10次，接着主线程循环100，接着又回到子线程循环10次，接着再回到主线程又循环100，如此循环50次
 * @author Lian
 */
public class BlockingQueueCommunicate {

	public static void main(String[] args) {
		final Bussniss2 bs = new Bussniss2();
		
		//子线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<10; i++){
					bs.sub(i);
				}
			}
		}).start();
		
		//主线程
		for(int i=0; i<10; i++){
			bs.main(i);
		}
	}
}
class Bussniss2{
	
	BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
	BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
	
	{
		try {
			queue2.put(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void sub(int i){
		try{
			queue1.put(1);
			
			for(int j=0; j<10; j++){
				System.out.println("Sub thread i="+(i+1)+",j="+(j+1));
			}
			
			queue2.take();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void main(int i){
		try{
			queue2.put(1);
			
			for(int j=0; j<100; j++){
				System.out.println("Main thread i="+(i+1)+",j="+(j+1));
			}
			queue1.take();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
